/*
 *	Copyright © 2013 Changsha Shishuo Network Technology Co., Ltd. All rights reserved.
 *	长沙市师说网络科技有限公司 版权所有
 *	http://www.shishuo.com
 */

package com.shishuo.cms.tag;

import com.shishuo.cms.entity.vo.ArticleVo;
import com.shishuo.cms.entity.vo.FolderVo;
import com.shishuo.cms.entity.vo.PageVo;
import com.shishuo.cms.exception.FolderNotFoundException;
import com.shishuo.cms.plugin.TagPlugin;
import com.shishuo.cms.service.ArticleService;
import com.shishuo.cms.service.FolderService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static freemarker.template.ObjectWrapper.BEANS_WRAPPER;

/**
 * @author Herbert
 */
@Service
public class ArticlePageTag extends TagPlugin {

    private static String DEFAULT_SORT = "sort asc , createTime desc";
    @Autowired
    private ArticleService articleService;

    @Autowired
    private FolderService folderService;

    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {

        PageVo<ArticleVo> pageVo;
        //  当前页
        Integer p = ((TemplateNumberModel) params.get("p")).getAsNumber().intValue();
        //  行数
        Integer rows = ((TemplateNumberModel) params.get("rows")).getAsNumber().intValue();

        //  排序参数
        String paramSort = new String(DEFAULT_SORT);
        if (params.get("sort") instanceof TemplateScalarModel) {
            paramSort = ((TemplateScalarModel) params.get("sort")).getAsString();
        }

        //  是否包含子栏目
        Boolean paramHasSub = params.get("subFolder") != null && ((TemplateBooleanModel) params.get("subFolder")).getAsBoolean();


        // 栏目参数 允许多个值 用逗号隔开
        List<Long> paramFolderIds = new ArrayList<Long>();
        if (params.get("folderIds") instanceof TemplateScalarModel) {
            for (String folderId : ((TemplateScalarModel) params.get("folderIds")).getAsString().split(",")) {
                paramFolderIds.add(Long.parseLong(folderId));
            }
        }


        //栏目id
        List<Long> folderIds = new ArrayList<Long>(paramFolderIds);
        // 获取父栏目下的内容 如果有subFolder参数 则包括子栏目的内容
        if (paramHasSub) {
            for (long parentId : paramFolderIds) {
                try {
                    folderIds.addAll(this.getArticlePageByFolderFatherId(parentId));
                } catch (FolderNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        try {
            pageVo = articleService.getArticlePageByFolderId(p, rows, paramSort, folderIds.toArray(new Long[folderIds.size()]));
            env.setVariable("tag_article_page", BEANS_WRAPPER.wrap(pageVo));
        } catch (FolderNotFoundException e) {
            e.printStackTrace();
        }

        body.render(env.getOut());
    }

    /**
     * 遍历当前栏目下的所有子栏目
     *
     * @param folderId
     * @return
     * @throws FolderNotFoundException
     */
    public List<Long> getArticlePageByFolderFatherId(Long folderId) throws FolderNotFoundException {
        List<FolderVo> folderVoList = folderService.getFolderListByFolderFatherIdLoop(folderId);
        Long[] folderIds = new Long[folderVoList.size()];
        for (int i = 0; i < folderVoList.size(); i++) {
            folderIds[i] = folderVoList.get(i).getFolderId();
        }
        return Arrays.asList(folderIds);
    }
}